import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'


Vue.use(VueRouter)

const routes = [

  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import('../views/goods.vue')
  },
  {
    path: '/goods/detail/:id',
    name: 'goodsDetail',
    component: () => import('../views/GoodsDetail.vue')
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/about.vue')
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('../views/order.vue'),
    meta: { requiresAuth: true }
  },

]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  const user = localStorage.getItem('user');

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token || !user) {
      next({
        path: '/',
        query: { redirect: to.fullPath }
      });
      store.commit('setShowLogin', true);
    } else {
      next();
    }
  } else {
    next();
  }

  if (token && user && store) {
    store.commit('setUser', JSON.parse(user));
  }
});

export default router
